/*
 *  RobotSystem.h
 *  vorpal
 *
 *  Created by rwebb on 4/05/08.
 *
 */

#ifndef VORPAL_GAMESYSTEM_H
#define VORPAL_GAMESYSTEM_H

#include "Objects.h"
#include "VM.h"

using namespace std;

namespace Vorpal{

	class GameSystem : public System{
	public:
		GameSystem(const char *sourcePath = 0) : code(0), vm(this){ 
			Compile(sourcePath);
			if(code){
				vm.PushPtr(this); // self
				vm.Execute(code, 1);
				vm.Drop(vm.Depth());
			}
		}

		virtual ~GameSystem(){
			if(code){ delete[] code; }
		}
				
		void Run(const char *method, double *arg, uint numArgs){
			if(!code){ return; }
			Handle<Object> methodCode = Get(msg(method), &vm);
			if(typeid(*methodCode.Ptr()) == typeid(Code)){
				vm.PushPtr(this); // self
				for(uint i = 0; i < numArgs; ++i){
					vm.PushPtr(new Number(arg[i]));
				}
				vm.Execute( ((Code*)methodCode.Ptr())->CodePtr(), numArgs + 1 );
				vm.Drop(vm.Depth());
			}
		}
		
		virtual bool Receive(Message msg, uint numArgs, VM *vm);				
		virtual bool PassByValue(){ return false; }
		virtual bool CopyOnClone(){ return false; }
		virtual Object *CopyOf() const{ Failure(ERR_OBJ_CANNOT_COPYOF); return 0; }

		virtual void Print() const{
			printf("System\n");
		}
		
	protected:
		virtual void MakeClone(Object *clone){ Failure(ERR_OBJ_CANNOT_CLONE); }
		virtual void Compile(const char *sourcePath);		

	private:
		Cell *code;
		VM vm;
	};
}

#endif
